package com.codechuan.demo;

import static com.codechuan.demo.common.Constant.context;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSONObject;
import com.codechuan.demo.common.Constant;
import com.codechuan.demo.dto.SysKey;
import com.codechuan.demo.dto.SysUserAccount;
import com.codechuan.demo.dto.SysUserConfig;
import com.codechuan.demo.ui.login.LoginActivity;
import com.codechuan.demo.ui.registerVip.RegisterVipActivity;
import com.codechuan.demo.utils.DeviceIdUtil;
import com.codechuan.demo.utils.DialogUtil;
import com.codechuan.demo.utils.HttpControllerUtil;
import com.codechuan.demo.utils.MyHttpUtil;


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Button button;
    TextView account;
    TextView password;
    CheckBox saveInfo;
    CheckBox startDw;
    String uuid;
    private static final int REQUEST_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        context = this;
        account = findViewById(R.id.account);
        password = findViewById(R.id.password);
        button = findViewById(R.id.login);
        button.setOnClickListener(this);
        saveInfo = findViewById(R.id.saveInfo);

        Button register = findViewById(R.id.register);
        register.setOnClickListener(this);
        // 获取主线程
        Constant.handler = new Handler(getMainLooper());
        // 默认为登录模式
        RadioButton login_check = findViewById(R.id.login_check);
        login_check.setChecked(true);
        // 获取是否开启实时定位
        startDw = findViewById(R.id.start_dw);
        // 初始化线程池
        Constant.executorService = Executors.newFixedThreadPool(10);

        // 获取配置文件
        HashMap<String, String> accountMap = getAccount();
        account.setText(accountMap.get("account"));
        password.setText(accountMap.get("password"));
        uuid = accountMap.get("uuid");
        saveInfo = findViewById(R.id.saveInfo);
        saveInfo.setChecked(Objects.equals(accountMap.get("isCheck"), "1"));
        startDw.setChecked(Objects.equals(accountMap.get("startDw"), "1"));

        // 初始化分辨率
        Constant.dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(Constant.dm);

        // 开启悬浮窗
        checkAndRequestPermission();

        Constant.mediaPlayerPK = MediaPlayer.create(this, R.raw.blok);


    }

    private void checkAndRequestPermission() {
        if (!Settings.canDrawOverlays(this)) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, REQUEST_CODE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            if (!Settings.canDrawOverlays(this)) {
                Toast.makeText(this, "请打开悬浮权限", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e("-----", "onResume");
    }


    @Override
    public void onClick(View view) {
        // 获取设备唯一标识码
        String deviceId = DeviceIdUtil.getDeviceId(this);

        // 登录
        if (view.getId() == R.id.login) {
            Constant.mediaPlayer = MediaPlayer.create(this, R.raw.ss);
            TextView account = findViewById(R.id.account);
            String accountString = account.getText().toString();
            if (accountString.isEmpty()) {
                DialogUtil.showDialog(this, "账号不能为空!");
                return;
            }
            TextView password = findViewById(R.id.password);
            String passwordSting = password.getText().toString();
            if (passwordSting.isEmpty()) {
                DialogUtil.showDialog(this, "密码不能为空!");
                return;
            }

            RadioButton login_check = findViewById(R.id.login_check);
            RadioButton login_topUp = findViewById(R.id.login_topUp);
            if (!login_check.isChecked() && !login_topUp.isChecked()) {
                DialogUtil.showDialog(this, "请选择登录,或者注册方式!");
                return;
            }
            TextView key = findViewById(R.id.key);
            String keySting = key.getText().toString();
            if (keySting.isEmpty() && login_topUp.isChecked()) {
                DialogUtil.showDialog(this, "卡密不能为空!");
                return;
            }
            // 访问数据库
            Constant.executorService.execute(new Runnable() {
                @Override
                public void run() {
                    if (login_topUp.isChecked()) {
                        // 充值逻辑
                        JSONObject loginResult = MyHttpUtil.login(accountString, passwordSting, keySting, "1", deviceId);
                        if (loginResult.getString("code").equals("500")) {
                            Constant.handler.post(() -> DialogUtil.showDialog(MainActivity.this, loginResult.getString("message")));
                            button.setText("登录助手");
                            return;
                        } else {
                            Constant.handler.post(() -> DialogUtil.showDialog(MainActivity.this, loginResult.getString("message")));
                            button.setText("登录助手");
                        }
                    } else {
                        // 设置全局账户名称
                        Constant.USER_ACCOUNT = accountString;
                        Constant.USER_PWD = passwordSting;
                        Constant.deviceId = deviceId;
                        // 登录逻辑
                        JSONObject loginResult = MyHttpUtil.login(accountString, passwordSting, keySting, "0", deviceId);
                        if (loginResult == null){
                            Constant.handler.post(()->{
                                DialogUtil.showDialog(context, "服务器异常!");
                            });
                            return;
                        }
                        if (loginResult.getString("code").equals("500")) {
                            button.setText("登录助手");
                            // 判断是否是解绑 如果是就弹窗
                            if (loginResult.getString("message").equals("请先解绑!")) {
                                Constant.handler.post(()->{
                                    AlertDialog.Builder showDialog = DialogUtil.showNoBind("是否进行解绑?", "点击确认即刻解绑,每周有五次免费解绑机会,请珍惜,请勿移交账号给他人!");
                                    showDialog.show();
                                });

                            } else {
                                Constant.handler.post(() -> DialogUtil.showDialog(MainActivity.this, loginResult.getString("message")));
                                return;
                            }
                        } else {
                            // 获取版本号
                            String version = loginResult.getString("data");
                            if (version.equals(Constant.app_version)){
                                Constant.is_zx = true;
                            }
                            Constant.handler.post(() -> DialogUtil.showDialog(MainActivity.this, loginResult.getString("message")));
                            button.setText("登录助手");
                            // 设置全局是否开启实时定位
                            Constant.startDwChecked = startDw.isChecked();

                            // 判断用户名是不是空的
                            if (Constant.USER_ACCOUNT == null || Constant.USER_ACCOUNT.isEmpty()) {
                                DialogUtil.showDialog("错误", "未检测到账号请重新登录.").show();
                            }

                            // 是否保存配置
                            if (saveInfo.isChecked()) {
                                saveAcount(accountString, passwordSting, "1", Constant.startDwChecked ? "1" : "0");
                            } else {
                                saveAcount("", "", "0", Constant.startDwChecked ? "1" : "0");
                            }

                            // 读取用户配置
                            SysUserConfig sysUserConfig = MyHttpUtil.selectUserConfig();
                            Constant.handler.post(() -> DialogUtil.showDialog(MainActivity.this, "登录成功,初始化数据中,请耐心等待!"));

                            // 判断是否开启了实时定位
                            CheckBox ss_dw = findViewById(R.id.start_dw);
                            Constant.SS_DW_CHECKED = ss_dw.isChecked();

                            // 读取配置文件赋值给常量
                            if (sysUserConfig != null) {
                                String jdMs = sysUserConfig.getJdMs();
                                if (jdMs.equals("0"))
                                    Constant.CJ_ORDER = true;
                                if (jdMs.equals("1"))
                                    Constant.SN_ORDER = true;
                                if (jdMs.equals("2"))
                                    Constant.XC_ORDER = true;

                                String rsMs = sysUserConfig.getRsMs();
                                if (rsMs.equals("0")) {
                                    Constant.APP_IS_CHECK = true;
                                } else {
                                    Constant.XCX_IS_CHECK = true;
                                }

                                Constant.MIN_MONEY = Integer.parseInt(sysUserConfig.getMinMoney());
                                Constant.MAX_MONEY = Integer.parseInt(sysUserConfig.getMaxMoney());

                                if (sysUserConfig.getGlqSelect() != null) {
                                    if (sysUserConfig.getGlqSelect().equals("0"))
                                        Constant.ZJ_DX = true;
                                    if (sysUserConfig.getGlqSelect().equals("1"))
                                        Constant.YD_GS = true;
                                    if (sysUserConfig.getGlqSelect().equals("2"))
                                        Constant.LX_QD = true;
                                }

                                Constant.MAX_STARTING_POINT_DISTANCE = sysUserConfig.getMin_start();

                                if (sysUserConfig.getPx_gz().equals("0"))
                                    Constant.ZN_PX_CHECK = true;
                                if (sysUserConfig.getPx_gz().equals("1"))
                                    Constant.ZJ_CHECK = true;
                                if (sysUserConfig.getPx_gz().equals("2"))
                                    Constant.ZZ_CHECK = true;
                                if (sysUserConfig.getPx_gz().equals("3"))
                                    Constant.ZG_CHECK = true;

                                Constant.PC_PERSON_CHECKBOX = !sysUserConfig.getPc_check().equals("0");
                                Constant.PC_MIN_NUMBER = Integer.parseInt(sysUserConfig.getMin_pc_number());
                                Constant.PC_MAX_NUMBER = Integer.parseInt(sysUserConfig.getMax_pc_number());

                                Constant.DX_PERSON_CHECKBOX = !sysUserConfig.getDx_check().equals("0");
                                Constant.DX_MIN_NUMBER = Integer.parseInt(sysUserConfig.getMin_dx_number());
                                Constant.DX_MAX_NUMBER = Integer.parseInt(sysUserConfig.getMax_dx_number());

                                Constant.SS_PERSON_CHECKBOX = !sysUserConfig.getSs_check().equals("0");
                                Constant.SS_MIN_NUMBER = Integer.parseInt(sysUserConfig.getMin_ss_number());
                                Constant.SS_MAX_NUMBER = Integer.parseInt(sysUserConfig.getMax_ss_number());

                                String djCheck = sysUserConfig.getDj_check();
                                if (djCheck == null) {
                                    Constant.DJ_CHECK = false;
                                    Constant.DJ_MIN_MONEY = 1.5;
                                } else {
                                    Constant.DJ_CHECK = !sysUserConfig.getDj_check().equals("0");
                                    Constant.DJ_MIN_MONEY = Double.parseDouble(sysUserConfig.getMin_dj_money());
                                }
                            }

                            // 置空主号信息
                            Constant.isStart = false; // 避免用户自己跳回登录页面
                            Constant.MAIN_TOKEN = null;
                            Constant.MAIN_TICKET = null;
                            Constant.MAIN_ERROR_NUMBER = 0;
                            Constant.MAIN_ACCOUNT_STATUS = "主号不存在,重新打开软件或设置主号.";

                            // 获取用户token表
                            MyHttpUtil.getUserTokenList(accountString);
                            Intent intent = new Intent();
                            intent.setClass(MainActivity.this, LoginActivity.class);
                            startActivity(intent);
                        }
                    }
                }
            });
            Button button = findViewById(R.id.login);
            button.setText("校验中...");
        }
        // 注册按钮事件
        if (view.getId() == R.id.register) {
            Intent intent = new Intent();
            intent.setClass(MainActivity.this, RegisterVipActivity.class);
            startActivity(intent);
        }
    }


    private void saveAcount(String account, String password, String isCheck, String startDwString) {
        String fileName = "account.txt";              //文件名称
        // isCheck 0不保存  1保存 实时定位 开启为1 未开启为0
        String content = account + "," + password + "," + isCheck + "," + startDwString;             //保存数据
        FileOutputStream fos = null;
        try {
            fos = this.openFileOutput(fileName, MODE_PRIVATE);
            fos.write((content.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private HashMap<String, String> getAccount() {
        String content = "";
        FileInputStream fis = null;
        try {
            fis = this.openFileInput("account.txt");    //获取文件输入流对象
            byte[] buffer = new byte[fis.available()];  //创建缓冲区，并获取文件长度
            fis.read(buffer);                           //将文件内容读取到buffer缓冲区
            content = new String(buffer);               //转换成字符串
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();                        //关闭输入流
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        HashMap<String, String> hashMap = new HashMap<>();
        if (content.isEmpty()) {
            hashMap.put("account", "");
            hashMap.put("password", "");
            hashMap.put("isCheck", "0");
            hashMap.put("startDw", "0");
        } else {
            String[] split = content.split(",");
            hashMap.put("account", split[0]);
            hashMap.put("password", split[1]);
            hashMap.put("isCheck", split[2]);
            try {
                hashMap.put("startDw", split[3]);
            } catch (Exception e) {
                hashMap.put("startDw", "0");
            }
        }
        return hashMap;
    }
}